package com.ruoyi.system.controller;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.system.domain.HyrjAppointmentAction;
import com.ruoyi.system.domain.HyrjLaundryPattern;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.service.*;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.HyrjMachine;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 【请填写功能名称】Controller
 *
 * @author ruoyi
 * @date 2024-03-07
 */
@RestController
@RequestMapping("/system/machine")
public class HyrjMachineController extends BaseController {
    @Autowired
    private IHyrjMachineService hyrjMachineService;
    @Autowired
    private IHyrjAppointmentActionService hyrjAppointmentActionService;
    @Autowired
    private ISysDictDataService sysDictDataService;
    @Autowired
    private IHyrjLaundryPatternService hyrjLaundryPatternService;
    @Autowired
    private ISysUserService iSysUserService;
    @Autowired
    private ISysRoleService iSysRoleService;


    /**
     * 查询【请填写功能名称】列表
     */
    @PreAuthorize("@ss.hasPermi('system:machine:list')")
    @GetMapping("/list")
    public TableDataInfo list(HyrjMachine hyrjMachine) {
        startPage();
        List<HyrjMachine> list = hyrjMachineService.selectHyrjMachineList(hyrjMachine);
        return getDataTable(list);
    }


    /**
     * 查询【请填写功能名称】列表
     */
    @PreAuthorize("@ss.hasPermi('system:machine:list')")
    @GetMapping("/listByTime")
    public TableDataInfo listByTime(HyrjMachine hyrjMachine) {
        startPage();


//        List<String> roleKeyList = new ArrayList<>();
//        SysUser sysUser = iSysUserService.selectUserById(getUserId());
//        if (null != sysUser) {
//            List<Long> longs = iSysRoleService.selectRoleListByUserId(sysUser.getUserId());
//            for (Long aLong : longs) {
//                SysRole sysRole = iSysRoleService.selectRoleById(aLong);
//                if (null != sysRole) {
//                    roleKeyList.add(sysRole.getRoleKey());
//                }
//            }
//        }
//        if (!roleKeyList.contains("amdin")) {
//            hyrjMachine.setCreateBy(String.valueOf(getUserId()));
//        }

        List<HyrjAppointmentAction> hyrjAppointmentActionList = hyrjAppointmentActionService.selectHyrjAppointmentActionList(new HyrjAppointmentAction());

        Map<String, List<HyrjAppointmentAction>> hyrjAppointmentActionListMap = hyrjAppointmentActionList.stream()
                .collect(Collectors.groupingBy(HyrjAppointmentAction::getMachineNo));

        hyrjMachine.setMachineStatus("2");
        List<HyrjMachine> list = hyrjMachineService.selectHyrjMachineList(hyrjMachine);

        for (HyrjMachine machine : list) {

            List<HyrjAppointmentAction> hyrjAppointmentActionList1 = hyrjAppointmentActionListMap.get(machine.getMachineNo());

            int appointmentNumberList = 0;
            if (null != hyrjAppointmentActionList1) {

                for (HyrjAppointmentAction hyrjAppointmentAction : hyrjAppointmentActionList1) {

                    if (null != hyrjAppointmentAction.getLaundryPattern()) {

                        if (hyrjAppointmentAction.getAppointmentStatus().equals("1")) {
                            appointmentNumberList = appointmentNumberList + 1;
                        }

                        HyrjLaundryPattern hyrjLaundryPattern = hyrjLaundryPatternService.selectHyrjLaundryPatternByLaundryPattern(hyrjAppointmentAction.getLaundryPattern());

                        if (null != hyrjLaundryPattern) {
                            Date appointmentTime = hyrjAppointmentAction.getLaundryStartTime();

                            // 将 laundry_pattern 转换为毫秒数
                            long laundryPatternDurationMillis = Integer.parseInt(hyrjLaundryPattern.getLaundryTime()) * 60 * 1000;

                            // 获取当前时间的毫秒数
                            long nowMillis = System.currentTimeMillis();

                            // 将 appointmentTime 转换为毫秒数
                            long appointmentTimeMillis = appointmentTime.getTime();

                            // 计算新的时间（appointmentTime 加上 laundry_pattern）的毫秒数
                            long newTimeMillis = appointmentTimeMillis + laundryPatternDurationMillis;

                            // 计算新的时间与当前时间的差值（毫秒数）
                            long timeDifferenceMillis = newTimeMillis - nowMillis;

                            // 如果 timeDifferenceMillis 是负数，表示当前时间已经超过了新的时间
                            if (timeDifferenceMillis < 0) {
                                machine.setRemainingTime("");
                            } else {
                                // 将时间差转换为 Date 类型（如果需要的话）
                                Date timeDifferenceDate = new Date(timeDifferenceMillis);

                                // 这里通常不会直接将时间差转换为 Date，因为 Date 表示一个具体的时间点
                                // 而是可能会将时间差转换为小时、分钟等更容易理解的单位
                                long hours = timeDifferenceMillis / (60 * 60 * 1000);
                                long minutes = (timeDifferenceMillis % (60 * 60 * 1000)) / (60 * 1000);

                                String remainingTime = hours + "小时" + minutes + "分钟";

                                machine.setRemainingTime(remainingTime);
                                System.out.println("时间差（小时）: " + hours);
                                System.out.println("时间差（分钟）: " + minutes);
                            }
                        }
                    }
                }
                //预约人数
                machine.setAppointmentNumber(appointmentNumberList);
            }
        }
        return getDataTable(list);
    }

    /**
     * 导出【请填写功能名称】列表
     */
    @PreAuthorize("@ss.hasPermi('system:machine:export')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, HyrjMachine hyrjMachine) {
        List<HyrjMachine> list = hyrjMachineService.selectHyrjMachineList(hyrjMachine);
        ExcelUtil<HyrjMachine> util = new ExcelUtil<HyrjMachine>(HyrjMachine.class);
        util.exportExcel(response, list, "【请填写功能名称】数据");
    }

    /**
     * 获取【请填写功能名称】详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:machine:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(hyrjMachineService.selectHyrjMachineById(id));
    }

    /**
     * 新增【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('system:machine:add')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody HyrjMachine hyrjMachine) {
        hyrjMachine.setCreateBy(String.valueOf(getUserId()));
        return toAjax(hyrjMachineService.insertHyrjMachine(hyrjMachine));
    }

    /**
     * 修改【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('system:machine:edit')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody HyrjMachine hyrjMachine) {
        return toAjax(hyrjMachineService.updateHyrjMachine(hyrjMachine));
    }

    /**
     * 删除【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('system:machine:remove')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(hyrjMachineService.deleteHyrjMachineByIds(ids));
    }


    /**
     * 修改【请填写功能名称】
     */
    @PostMapping("/update")
    public AjaxResult update(@RequestBody HyrjMachine hyrjMachine) {
        hyrjMachine.setUserId(getLoginUser().getUserId());
        return toAjax(hyrjMachineService.updateHyrjAppointmentAction(hyrjMachine));
    }
}
